package com.example.manage.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.StringRedisSerializer;

@Configuration
public class RedisConfig {

    //创建 RedisConnectionFactory Bean，用于建立与 Redis 服务器的连接
    @Bean
    public RedisConnectionFactory redisConnectionFactory(Appconfig appConfig) {
        return new LettuceConnectionFactory(appConfig.getRedisHost(), appConfig.getRedisPort());
    }

    //创建 RedisTemplate Bean，提供对 Redis 数据结构（如字符串、哈希、列表等）的通用操作接口
    //全部使用 StringRedisSerializer，确保键和值以 UTF-8 字符串 形式存储，提升可读性和兼容性
    @Bean
    public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory) {
        RedisTemplate<String, Object> template = new RedisTemplate<>();
        template.setConnectionFactory(factory);
        // ✅ 修改值序列化器
        template.setKeySerializer(new StringRedisSerializer());
        template.setValueSerializer(new StringRedisSerializer()); // 改为字符串序列化

        template.setHashKeySerializer(new StringRedisSerializer());
        template.setHashValueSerializer(new StringRedisSerializer());

        template.afterPropertiesSet();

        return template;
    }

}
